package com.itclass.auth.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itclass.auth.pojo.db.Product;
import com.itclass.auth.pojo.db.Result;
import com.itclass.auth.pojo.dto.ResultPageDTO;
import com.itclass.auth.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.DateUtils;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;


    @GetMapping("/listPage/{currentPage}/{pageSize}")
    public Result<ResultPageDTO<Product>> listPage(@PathVariable("currentPage") Integer currentPage,@PathVariable("pageSize") Long pageSize) {

        Page<Product> productPage = productService.listPage(currentPage,pageSize);

        ResultPageDTO<Product> resultPageDTO = new ResultPageDTO<>();

        resultPageDTO.setCurrentPage(productPage.getCurrent());
        resultPageDTO.setPageSize(productPage.getSize());
        resultPageDTO.setData(productPage.getRecords());
        resultPageDTO.setTotalCount(productPage.getTotal());
        resultPageDTO.setTotalPage(productPage.getPages());
        return Result.ok(resultPageDTO);
    }


    @PostMapping("/add")
    public Result add(@RequestBody Product product) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        product.setCreateName(principal.toString());
        product.setCreateDate(new Date());
        boolean save = productService.save(product);

        return save ? Result.ok() : Result.fail();
    }


    @GetMapping("/remove/{id}")
    public Result remove(@PathVariable("id") Long id) {
        boolean save = productService.removeById(id);
        return save ?Result.ok():Result.fail();
    }


    @PostMapping("/update")
    public Result update(@RequestBody Product product) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();

        product.setUpdateDate(new Date());
        product.setUpdateName(principal.toString());
        boolean save = productService.updateById(product);
        return save ? Result.ok() : Result.fail();
    }
}
